package com.maincode.fragment.login;


import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.example.risen.androidwcc.R;
import com.lidroid.xutils.ViewUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.client.HttpRequest;
import com.lidroid.xutils.view.annotation.ViewInject;
import com.lidroid.xutils.view.annotation.event.OnClick;
import com.maincode.activity.SinglePageActivity;
import com.maincode.activity.IndexActivity;
import com.maincode.model.UserInfo;
import com.util.HttpUrl;
import com.util.SystemParams;
import com.util.Tools;
import com.util.xutil.HttpParams;
import com.util.xutil.HttpRequestCallBack;
import com.util.xutil.HttpUtils;
import com.view.HeadBar;

import java.util.Timer;
import java.util.TimerTask;

/**
 * 注册第二步 发送验证码
 */
public class Login3Fragment extends Fragment {

    @ViewInject(R.id.login_phone_num)
    EditText login_phone_num;
    @ViewInject(R.id.etPhoneNum)
    EditText etPhoneNum;
    @ViewInject(R.id.login_code)
    EditText login_code;

    @ViewInject(R.id.get_code)
    TextView get_code;

    HeadBar headBar;
    View v;
    String phoneNum;
    int n = 60; //60秒获取一次验证码
    SinglePageActivity activity;

    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        activity = (SinglePageActivity) getActivity();
        v = inflater.inflate(R.layout.fragment_login3, container, false);
        ViewUtils.inject(this, v);
        init();
        return v;
    }

    private void init() {
        headBar = (HeadBar) v.findViewById(R.id.headBar);
        headBar.setBarText("注册");
        headBar.setBarRightText("下一步");
        headBar.setBarRightSH(View.INVISIBLE);
    }

    @OnClick(R.id.get_code)
    private void codeClick(View v) {
        phoneNum = etPhoneNum.getText().toString().trim();
        if (phoneNum.length() == 0) {
            activity.showToast("请填写手机号");
            return;
        }
        if (!Tools.isMobileNum(phoneNum)) {
            activity.showToast("手机号不正确");
            return;
        }
        HttpParams httpParams = new HttpParams(HttpUrl.SENDSMSCODE);
        httpParams.putString("phone", phoneNum);
        httpParams.putString("phoneRegisted", "1");
        HttpUtils httpUtils = HttpUtils.getInstance();
        httpUtils.send(HttpRequest.HttpMethod.POST, httpParams.toString(), new HttpRequestCallBack<String>(String.class, getActivity(), "正在获取验证码") {

            @Override
            protected void onSuccess(String s) {
                JSONObject jsonObject = JSON.parseObject(s);
                if (s.contains("true")) {
                    setCodeDate();
//                    code = jsonObject.getString("data");
                    activity.showToast("验证码已发送(" + jsonObject.getString("data") + ")");
                } else {
                    if (jsonObject.getString("data").equals("PHONE_EXISTED")) {
                        showVFDialog();
                    }
                }
            }
        });
    }

    Timer timer;

    private void setCodeDate() {
        timer = new Timer();
        timer.schedule(new TimerTask() {
            @Override
            public void run() {
                n--;
                handler.sendEmptyMessage(n);
            }
        }, 1000, 1000);
    }

    Handler handler = new Handler() {
        @Override
        public void dispatchMessage(Message msg) {
            super.dispatchMessage(msg);
            if (msg.what > 0) {
                get_code.setTextColor(getResources().getColor(R.color.color_cccccc));
                get_code.setText("重新获取(" + msg.what + ")");
                get_code.setEnabled(false);
            } else {
                if (timer != null)
                    timer.cancel();
                get_code.setTextColor(getResources().getColor(R.color.black));
                n = 60;
                get_code.setText("获取验证码");
                get_code.setEnabled(true);
            }
        }
    };

    /**
     * 注册账号
     */
    private void registUser(String code, String pwd) {
        HttpParams httpParams = new HttpParams(HttpUrl.REGISTBYSMSCODE);
        httpParams.putString("phone", phoneNum);
        httpParams.putString("originPassword", pwd);
        httpParams.putString("smscode", code);
        HttpUtils httpUtils = HttpUtils.getInstance();
        httpUtils.send(HttpRequest.HttpMethod.POST, httpParams.toString(), new HttpRequestCallBack<String>(String.class, getActivity(), "正在注册，请稍后...") {

            @Override
            protected void onSuccess(String s) {
                JSONObject jsonObject = JSONObject.parseObject(s);
                if (s.contains("true")) {
                    UserInfo userInfo = new UserInfo();
                    if (jsonObject.containsKey("data")) {
                        userInfo.token = jsonObject.getString("data");
                        activity.saveUserInfo(userInfo);
                        activity.fragmentManager("RegisterPerfectInfo", "");
//                        activity.startActivity(new Intent(activity, IndexActivity.class));
//                        activity.finish();
                    }
                } else {
                    String msg = SystemParams.getInstance().getErrorMsg(jsonObject.getString("data"));
                    activity.showDialog(msg);
                }
            }

            @Override
            public void onFailure(HttpException arg0, String arg1) {
                super.onFailure(arg0, arg1);
                activity.showToast("注册失败");
            }
        });
    }

    /**
     * 下一步
     */
    @OnClick(R.id.tvRegister)
    private void nextClick(View v) {
        phoneNum = etPhoneNum.getText().toString().trim();
        String code = login_phone_num.getText().toString().trim();
        if (phoneNum.length() == 0) {
            activity.showToast("请填写手机号");
            return;
        }
        if (!Tools.isMobileNum(phoneNum)) {
            activity.showToast("手机号不正确");
            return;
        }
        if (code.length() == 0) {
            activity.showToast("请填写验证码");
            return;
        }
        if (code.length() < 4) {
            activity.showToast("验证码为4位");
            return;
        }
        RegisterCode(code);
    }

    private void RegisterCode(final String code) {
        HttpParams httpParams = new HttpParams(HttpUrl.getUrl(HttpUrl.SMSCODE));
        httpParams.putString("phone", phoneNum);
        httpParams.putString("smscode", code);
        HttpUtils httpUtils = HttpUtils.getInstance();
        httpUtils.send(HttpRequest.HttpMethod.POST, httpParams.toString(), new HttpRequestCallBack<String>(String.class, activity, "正在验证") {
            @Override
            protected void onSuccess(String s) {
                if (s.contains("true")) {
                    String pwd = login_code.getText().toString().trim();
                    if (pwd.length() == 0) {
                        activity.showToast("请填写密码");
                        return;
                    }
                    if (pwd.length() < 6) {
                        activity.showToast("密码为6位以上");
                        return;
                    }
                    activity.password = pwd;
                    activity.code = code;
                    activity.phone = phoneNum;
                    InputMethodManager inputMethodManager = (InputMethodManager) activity.getSystemService(Context.INPUT_METHOD_SERVICE);
                    inputMethodManager.hideSoftInputFromWindow(login_code.getWindowToken(), 0);
                    activity.fragmentManager("RegisterPerfectInfo", "");
                } else {
//                    activity.showToast("验证码错误");
                    return;
                }
            }
        });
    }

    @OnClick(R.id.go_back_tv)
    private void backLeft(View v) {
        activity.backFragment();
    }

    private void showVFDialog() {
        final AlertDialog dialog = new AlertDialog.Builder(getActivity()).create();
        View view = getActivity().getLayoutInflater().inflate(R.layout.view_regist_dialog, null);
        dialog.setView(view, 0, 0, 0, 0);
        dialog.show();
        Button btnResc = (Button) dialog.findViewById(R.id.btnResc);
        Button btnGoLogin = (Button) dialog.findViewById(R.id.btnGoLogin);
        btnResc.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                etPhoneNum.setText("");
                dialog.dismiss();
            }
        });
        btnGoLogin.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                activity.backFragment();
                dialog.dismiss();
            }
        });
    }

    @Override
    public void onStop() {
        super.onStop();
        if (timer != null)
            timer.cancel();
    }
}
